package org.opens.netty.chatServer.server.handle;

import cn.hutool.core.collection.CollectionUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.opens.netty.chatServer.message.GroupChatResponseMessage;
import org.opens.netty.chatServer.message.GroupCreateRequestMessage;
import org.opens.netty.chatServer.message.GroupCreateResponseMessage;
import org.opens.netty.chatServer.server.session.Group;
import org.opens.netty.chatServer.server.session.GroupSession;
import org.opens.netty.chatServer.server.session.GroupSessionFactory;

import java.util.Collections;
import java.util.List;
import java.util.Set;

@ChannelHandler.Sharable
public class GroupCreateRequestMessageHandle extends SimpleChannelInboundHandler<GroupCreateRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, GroupCreateRequestMessage msg) throws Exception {
        String groupName = msg.getGroupName();
        Set<String> members = msg.getMembers();
        GroupSession groupSession = GroupSessionFactory.getGroupSession();
        Group group = groupSession.createGroup(groupName, members);
        if (group == null) {
            // 向创建者发送成功创建消息
            GroupCreateResponseMessage groupCreateResponseMessage1 = new GroupCreateResponseMessage(true, groupName + "创建成功.");
            ctx.writeAndFlush(groupCreateResponseMessage1);

            // 想组中其他成员发送消息
            List<Channel> membersChannel = groupSession.getMembersChannel(groupName);
            if (CollectionUtil.isNotEmpty(membersChannel)) {
                for (Channel channel : membersChannel) {
                    GroupCreateResponseMessage groupCreateResponseMessage2 = new GroupCreateResponseMessage(true, "您已被拉入群聊(" + groupName + ")");
                    channel.writeAndFlush(groupCreateResponseMessage2);
                }
            }
        } else {
            GroupCreateResponseMessage groupCreateResponseMessage = new GroupCreateResponseMessage(false, groupName + "创建失败, 群已经存在!");
            ctx.writeAndFlush(groupCreateResponseMessage);
        }
    }
}
